import React, { useState } from 'react';
import { Form, Input, Button, Card, Typography, message } from 'antd';
import { MailOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { forgotPassword } from '../api/auth';

const { Title, Text } = Typography;

const ForgotPassword: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const onFinish = async (values: { email: string }) => {
    setLoading(true);
    // 显示提示信息，告知用户发送邮件可能需要一些时间
    message.loading('正在发送验证码，请稍候...', 0);
    try {
      const response = await forgotPassword(values.email);
      // 关闭loading消息
      message.destroy();
      if (response.code === 200) {
        message.success('验证码已发送，请检查您的邮箱');
        // 成功发送验证码后立即跳转到重置密码页面
        setTimeout(() => {
          navigate('/reset-password');
        }, 1500); // 1.5秒后跳转，让用户看到成功消息
      } else {
        message.error(response.message || '发送失败');
      }
    } catch (error) {
      // 关闭loading消息
      message.destroy();
      message.error('发送失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ 
      minHeight: '100vh', 
      display: 'flex', 
      alignItems: 'center', 
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    }}>
      <Card style={{ width: 400, boxShadow: '0 4px 12px rgba(0,0,0,0.15)' }}>
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ color: '#1890ff', marginBottom: 8 }}>
            忘记密码
          </Title>
          <Text type="secondary">
            输入您的邮箱地址，我们将发送验证码
          </Text>
        </div>

        <Form
          name="forgotPassword"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="email"
            rules={[
              { required: true, message: '请输入邮箱地址!' },
              { type: 'email', message: '请输入有效的邮箱地址!' }
            ]}
          >
            <Input 
              prefix={<MailOutlined />} 
              placeholder="邮箱地址" 
            />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              block
              style={{ height: 40 }}
            >
              发送验证码
            </Button>
          </Form.Item>
        </Form>

        <div style={{ textAlign: 'center', marginTop: 16 }}>
          <Link to="/login">
            <Text type="secondary">返回登录</Text>
          </Link>
        </div>
      </Card>
    </div>
  );
};

export default ForgotPassword; 